<template>
  <div class="container mx-auto p-4">
    <div v-if="product" class="max-w-4xl mx-auto">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
        <!-- 商品图片 -->
        <div class="bg-white p-4 rounded-lg">
          <img :src="product.image" 
               :alt="product.title" 
               class="w-full h-[400px] object-contain">
        </div>
        
        <!-- 商品信息 -->
        <div class="space-y-4">
          <h1 class="text-2xl font-bold">{{ product.title }}</h1>
          <p class="text-3xl font-bold text-red-600">¥{{ product.price }}</p>
          <p class="text-gray-600">{{ product.description }}</p>
          
          <!-- 数量选择 -->
          <div class="flex items-center space-x-4">
            <span>数量：</span>
            <button @click="quantity > 1 && quantity--"
                    class="px-3 py-1 border rounded">-</button>
            <span>{{ quantity }}</span>
            <button @click="quantity++"
                    class="px-3 py-1 border rounded">+</button>
          </div>
          
          <!-- 添加到购物车按钮 -->
          <button @click="addToCart"
                  class="w-full bg-blue-500 text-white py-3 rounded-lg hover:bg-blue-600">
            加入购物车
          </button>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else-if="productStore.loading" class="text-center py-8">
      <p>加载中...</p>
    </div>
    
    <!-- 商品未找到 -->
    <div v-else class="text-center py-8">
      <p>商品未找到</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useProductStore } from '../store/productStore'
import { useCartStore } from '../store/cartStore'

const route = useRoute()
const productStore = useProductStore()
const cartStore = useCartStore()
const quantity = ref(1)

const product = computed(() => {
  return productStore.getProductById(route.params.id)
})

const addToCart = () => {
  if (product.value) {
    for (let i = 0; i < quantity.value; i++) {
      cartStore.addToCart(product.value)
    }
    quantity.value = 1
  }
}

onMounted(() => {
  if (!productStore.products.length) {
    productStore.fetchProducts()
  }
})
</script> 